package main

import (
	"os"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var NotRun map[string]string
var NameNeedNotice map[string]string

func init() {
	NotRun = make(map[string]string)
	NameNeedNotice = make(map[string]string)
}

type cliOptions struct {
	Debug    bool
	LogLevel string
}

var cliOpts cliOptions

func newCliCommand() *cobra.Command {
	// rootCmd represents the base command when called without any sub commands
	rootCmd := &cobra.Command{
		Use:   "flower",
		Short: "flower: flow your image among the land, its flower",
		RunE: func(cmd *cobra.Command, args []string) error {
			return cmd.Help()
		},
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			return before(cmd)
		},
		SilenceUsage:          true,
		SilenceErrors:         true,
		DisableFlagsInUseLine: true,
	}
	setupRootCmd(rootCmd)
	addCommands(rootCmd)

	return rootCmd
}

func initLogging() error {
	logrusLvl, err := logrus.ParseLevel(cliOpts.LogLevel)
	if err != nil {
		return errors.Wrapf(err, "unable to parse log level")
	}
	logrus.SetLevel(logrusLvl)
	if cliOpts.Debug {
		logrus.SetLevel(logrus.DebugLevel)
	}
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
	logrus.SetOutput(os.Stdout)
	return nil
}

func before(cmd *cobra.Command) error {
	switch cmd.Use {
	case "", "help", "version":
		return nil
	}

	if err := initLogging(); err != nil {
		return err
	}

	return nil
}

func setupRootCmd(rootCmd *cobra.Command) {
	rootCmd.SetFlagErrorFunc(flagErrorFunc)
	rootCmd.PersistentFlags().StringVar(&cliOpts.LogLevel, "log-level", "error", "Log level to be used. Either \"debug\", \"info\", \"warn\" or \"error\"")
	rootCmd.PersistentFlags().BoolVarP(&cliOpts.Debug, "debug", "D", true, "Open debug mode")
	rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
}

func addCommands(cmd *cobra.Command) {
	cmd.AddCommand(
		newImageCmd(),
		newPlatformCmd(),
		newFlowCmd(),
		completionCmd,
	)
}

func flagErrorFunc(cmd *cobra.Command, err error) error {
	if err == nil {
		return nil
	}

	usage := ""
	if cmd.HasSubCommands() {
		usage = "\n\n" + cmd.UsageString()
	}
	return errors.Errorf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage)
}

// "completion" command to generate bash completion script
var completionCmd = &cobra.Command{
	Use:    "completion",
	Hidden: true,
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Root().GenBashCompletion(os.Stdout) // nolint
	},
}

func disableFlags(root *cobra.Command) {
	for _, c := range root.Commands() {
		c.DisableFlagsInUseLine = true
	}
}
